package com.yjw.rpc.v1;

import com.yjw.rpc.IoUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author: James Yin
 * @description:
 * @date: 2/10/2020 9:57 PM
 */
public class RpcProxyServer {

    private static final Map<String, Object> services = new ConcurrentHashMap<>();
    private static final Executor threadPool = Executors.newCachedThreadPool();

    public void addServices(String serviceName, Object service) {
        services.put(serviceName, service);
    }

    public void publish(int port) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                threadPool.execute(new ProcessHandler(socket, services));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtils.close(serverSocket);
        }
    }
}
